#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <linux/fb.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <wchar.h>
#include <sys/ioctl.h>

#include <ft2build.h>
#include <fonts_manager.h>


#include FT_FREETYPE_H
#include FT_GLYPH_H


FT_Vector     pen;
FT_GlyphSlot  slot;


static FT_Library g_tLibrary;
static FT_Face g_tFace;
static FT_GlyphSlot g_tSlot;


static int FT_FontInit(char *FontFileName, int FontSize)
{
    int ret;
    
	ret = FT_Init_FreeType( &g_tLibrary );			 
	if (ret)
    {
        printf("FT_Init_FreeType error\n");
    }
    
	
	ret = FT_New_Face(g_tLibrary, FontFileName, 0, &g_tFace ); 
	if (ret)
    {
        printf("FT_New_Face error\n");
    }
    else
	    slot = g_tFace->glyph;

	ret = FT_Set_Pixel_Sizes(g_tFace, FontSize, 0);
    if (ret)
    {
        printf("FT_Set_Pixel_Sizes error\n");
    }
    return 0;
}



static int FT_GetFontBitmap(unsigned int dwCode, PFontBitMap ptFontBitMap)
{
	int iError;
	int iPenX = ptFontBitMap->iCurOriginX;
	int iPenY = ptFontBitMap->iCurOriginY;

	iError = FT_Load_Char(g_tFace, dwCode, FT_LOAD_RENDER | FT_LOAD_MONOCHROME);
	if (iError)
	{
		printf("FT_Load_Char error for code : 0x%x\n", dwCode);
		return -1;
	}

	//DBG_PRINTF("iPenX = %d, iPenY = %d, bitmap_left = %d, bitmap_top = %d, width = %d, rows = %d\n", iPenX, iPenY, g_tSlot->bitmap_left, g_tSlot->bitmap_top, g_tSlot->bitmap.width, g_tSlot->bitmap.rows);
	ptFontBitMap->iXLeft    = iPenX + g_tSlot->bitmap_left;
	ptFontBitMap->iYTop     = iPenY - g_tSlot->bitmap_top;
	ptFontBitMap->iXMax     = ptFontBitMap->iXLeft + g_tSlot->bitmap.width;
	ptFontBitMap->iYMax     = ptFontBitMap->iYTop  + g_tSlot->bitmap.rows;
	ptFontBitMap->iBpp      = 1;
	ptFontBitMap->iPitch    = g_tSlot->bitmap.pitch;
	ptFontBitMap->pucBuffer = g_tSlot->bitmap.buffer;
	
	ptFontBitMap->iNextOriginX = iPenX + g_tSlot->advance.x / 64;
	ptFontBitMap->iNextOriginY = iPenY;

	return 0;
}



static FontOpr FT_FontOpr = {
    .name = "ft",
    .FontInit = FT_FontInit,
    .GetFontBitmap = FT_GetFontBitmap,
};




void RegisterFT(void)
{
    RegisterFontOpr(&FT_FontOpr);
}